package com.asimplefox.utils;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

import java.io.File;

@Slf4j
public class MP4ToAudio {

    public static void mp4ToAudio(File sourceFile, File outFile) {
        log.info("mp4-{} to wav-{} started", sourceFile.getAbsoluteFile(), outFile.getAbsoluteFile());
        FFmpegFrameGrabber frameGrabber1 = new FFmpegFrameGrabber(sourceFile);
        Frame frame = null;
        FFmpegFrameRecorder recorder = null;
        String fileName = null;
        try {
            frameGrabber1.start();
            recorder = new FFmpegFrameRecorder(outFile, frameGrabber1.getAudioChannels());
            recorder.setFormat("wav");
            recorder.setSampleRate(frameGrabber1.getSampleRate());
            recorder.setTimestamp(frameGrabber1.getTimestamp());
            recorder.setAudioQuality(0);
            recorder.start();
            int index = 0;
            while (true) {
                frame = frameGrabber1.grab();
                if (frame == null) {
                    log.info("处理完毕");
                    break;
                }
                if (frame.samples != null) {
                    recorder.recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
                }
                if (index % 200 == 0) log.debug("帧值={}", index);
                index++;
            }
            recorder.stop();
            recorder.release();
            frameGrabber1.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
